package com.canyou.redmine.ui;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.InputType;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.fastjson.JSON;
import com.allen.library.SuperTextView;
import com.canyou.redmine.R;
import com.canyou.redmine.model.Bean;
import com.canyou.redmine.model.Issue;
import com.canyou.redmine.model.Member;
import com.canyou.redmine.model.MemberPage;
import com.canyou.redmine.model.NewIssue;
import com.canyou.redmine.network.CanYouAPI;
import com.canyou.redmine.ui.base.BaseActivity;
import com.canyou.redmine.util.CanYouLog;
import com.loopj.android.http.TextHttpResponseHandler;
import com.sdsmdg.tastytoast.TastyToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * 任务详情
 *
 * @author ryk
 */
public class IssueActivity extends BaseActivity implements SuperTextView.OnClickListener {

    /**
     * 任务主题
     */
    private SuperTextView tvSubject;
    /**
     * 任务耗时
     */
    private SuperTextView tvEstimated;
    /**
     * 父任务
     */
    private SuperTextView tvParent;
    /**
     * 所属项目
     */
    private SuperTextView tvProject;
    /**
     * 任务状态
     */
    private SuperTextView tvStatus;
    /**
     * 指派
     */
    private SuperTextView tvAssigned;
    /**
     * 完成度
     */
    private SuperTextView tvDoneRatio;
    /**
     * 跟踪
     */
    private SuperTextView tvTracker;
    /**
     * 优先级
     */
    private SuperTextView tvPriority;
    /**
     * 开始时间
     */
    private SuperTextView tvStartDate;
    /**
     * 结束时间
     */
    private SuperTextView tvDueDate;

    private Issue issue;
    private NewIssue newIssue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_issue);
        Bundle bundle = getIntent().getExtras();
        String json = bundle.getString("issue", "");

        issue = JSON.parseObject(json, Issue.class);
        newIssue = new NewIssue();

        initUI();
    }

    private void initUI() {
        setBackButton(true);
        setTitle("#" + issue.getId());
        tvSubject = findViewById(R.id.tv_issue_subject);
        tvEstimated = findViewById(R.id.tv_issue_estimated);
        tvParent = findViewById(R.id.tv_issue_parent);
        tvProject = findViewById(R.id.tv_project_name);
        tvStatus = findViewById(R.id.tv_issue_status);
        tvAssigned = findViewById(R.id.tv_issue_assigned);
        tvDoneRatio = findViewById(R.id.tv_issue_done_ratio);
        tvTracker = findViewById(R.id.tv_issue_tracker);
        tvPriority = findViewById(R.id.tv_issue_priority);
        tvStartDate = findViewById(R.id.tv_issue_start_date);
        tvDueDate = findViewById(R.id.tv_issue_due_date);

        tvEstimated.setOnClickListener(this);
        tvStatus.setOnClickListener(this);
        tvAssigned.setOnClickListener(this);
        tvDoneRatio.setOnClickListener(this);
        tvTracker.setOnClickListener(this);
        tvPriority.setOnClickListener(this);

        loadData(issue);
    }

    private void loadData(Issue issue) {
        tvSubject.setLeftString(issue.getSubject());
        tvEstimated.setRightString(issue.getEstimated_hours() + "小时");
        if (issue.getParent() == null) {
            tvParent.setVisibility(View.GONE);
        } else {
            tvParent.setVisibility(View.VISIBLE);
            tvParent.setRightString("#" + issue.getParent().getId());
        }
        tvProject.setRightString(issue.getProject().getName());
        tvStatus.setRightString(issue.getStatus().getName());
        tvAssigned.setRightString(issue.getAssigned_to().getName());
        tvDoneRatio.setRightString(issue.getDone_ratio() + "%");
        tvTracker.setRightString(issue.getTracker().getName());
        tvPriority.setRightString(issue.getPriority().getName());
        tvStartDate.setRightString(issue.getStart_date());
        copyIssue();
    }

    /**
     * 更新副本
     */
    private void copyIssue() {
        newIssue.setId(issue.getId());
        newIssue.setSubject(issue.getSubject());
        newIssue.setDescription(issue.getDescription());
        newIssue.setProject_id(issue.getProject().getId());
        newIssue.setStatus_id(issue.getStatus().getId());
        newIssue.setPriority_id(issue.getPriority().getId());
        newIssue.setTracker_id(issue.getTracker().getId());
        newIssue.setAssigned_to_id(issue.getAssigned_to().getId());
        newIssue.setAuthor_id(issue.getAuthor().getId());
        newIssue.setCreated_on(issue.getCreated_on());
        newIssue.setDone_ratio(issue.getDone_ratio());
        newIssue.setDue_date(issue.getDue_date());
        newIssue.setEstimated_hours(issue.getEstimated_hours());
        newIssue.setStart_date(issue.getStart_date());
    }

    @Override
    public void onClick(View view) {

        int id = view.getId();

        switch (id) {
            case R.id.tv_issue_estimated:
                new MaterialDialog.Builder(this)
                        .title("请填写工时")
                        .content("耗时：")
                        .inputType(InputType.TYPE_CLASS_NUMBER)
                        .inputRange(1, 2)
                        .positiveText("更新")
                        .input("", "", false, new MaterialDialog.InputCallback() {
                            @Override
                            public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
                                newIssue.setEstimated_hours(issue.getEstimated_hours() + Integer.valueOf(input.toString()));
                                updateIssue();
                            }
                        })
                        .show();
                break;
            case R.id.tv_issue_status:
                getIssueStuats();
                break;
            case R.id.tv_issue_assigned:
                getMembers(issue.getProject().getId());
                break;
            case R.id.tv_issue_done_ratio:
                int size = 11;
                String[] array = new String[size];
                for (int i = 0; i < size; i++) {
                    array[i] = i * 10 + "%";
                }
                new MaterialDialog.Builder(this)
                        .title("请选择任务进度")
                        .items(array)
                        .itemsCallbackSingleChoice(
                                issue.getDone_ratio() / 10,
                                new MaterialDialog.ListCallbackSingleChoice() {
                                    @Override
                                    public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                        newIssue.setDone_ratio(which * 10);
                                        updateIssue();
                                        dialog.dismiss();
                                        return false;
                                    }
                                })
                        .show();
                break;
        }
    }

    /**
     * 更新任务单
     */
    private void updateIssue() {
        if (newIssue == null) {
            return;
        }
        CanYouAPI.updateIssue(this, newIssue, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                CanYouLog.i(responseString);
                AlertToast(responseString, TastyToast.ERROR);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                CanYouLog.i(responseString);
                if (statusCode == 200) {
                    getIssue(issue.getId());
                    AlertToast("更新成功", TastyToast.SUCCESS);
                } else {
                    AlertToast("更新失败啦", TastyToast.ERROR);
                }
            }

            @Override
            public void onStart() {
                super.onStart();
                showHUD();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeHUD();
            }
        });
    }

    /**
     * 获取任务单
     *
     * @param id 任务ID
     */
    private void getIssue(int id) {
        CanYouAPI.getIssueById(id, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                CanYouLog.i(responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                CanYouLog.i(responseString);
                String json = "";
                try {
                    JSONObject object = new JSONObject(responseString);
                    json = object.getString("issue");
                } catch (JSONException e) {
                    CanYouLog.e("json error:" + e.getLocalizedMessage());
                }
                issue = JSON.parseObject(json, Issue.class);
                loadData(issue);
            }
        });
    }

    /**
     * 获取任务状态集
     */
    private void getIssueStuats() {
        CanYouAPI.getIssueSatuses(new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                CanYouLog.i(responseString);
                String json = "";
                try {
                    JSONObject object = new JSONObject(responseString);
                    json = object.getString("issue_statuses");
                } catch (JSONException e) {
                    CanYouLog.e("json error:" + e.getLocalizedMessage());
                }
                final List<Bean> issue_statuses = JSON.parseArray(json, Bean.class);
                List<String> array = new ArrayList<>();
                for (Bean bean : issue_statuses) {
                    array.add(bean.getName());
                }

                new MaterialDialog.Builder(IssueActivity.this)
                        .title("请选择任务状态")
                        .items(array)
                        .itemsCallbackSingleChoice(
                                0,
                                new MaterialDialog.ListCallbackSingleChoice() {
                                    @Override
                                    public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                        newIssue.setStatus_id(issue_statuses.get(which).getId());
                                        updateIssue();
                                        return false;
                                    }
                                })
                        .show();
            }

            @Override
            public void onStart() {
                super.onStart();
                showHUD();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeHUD();
            }
        });
    }

    /**
     * 获取项目成员
     *
     * @param projectId 项目id
     */
    private void getMembers(int projectId) {
        CanYouAPI.getMembersByProjectId(projectId, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                CanYouLog.e(responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {

                MemberPage page = JSON.parseObject(responseString, MemberPage.class);
                final List<Member> members = page.getMemberships();
                List<String> array = new ArrayList<>();
                for (Member member : members) {
                    array.add(member.getUser().getName());
                }

                new MaterialDialog.Builder(IssueActivity.this)
                        .title("指派给：")
                        .items(array)
                        .itemsCallbackSingleChoice(
                                0,
                                new MaterialDialog.ListCallbackSingleChoice() {
                                    @Override
                                    public boolean onSelection(MaterialDialog dialog, View itemView,
                                                               int which, CharSequence text) {
                                        newIssue.setAssigned_to_id(members.get(which).getUser().getId());
                                        updateIssue();
                                        return false;
                                    }
                                })
                        .show();
                CanYouLog.i(responseString);
            }

            @Override
            public void onStart() {
                super.onStart();
                showHUD();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeHUD();
            }
        });
    }
}
